/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
主要功能：
1.从数据库查询结果中提取便签字段数据
2.处理便签的位置信息（是否首尾、是否唯一等）
3.提供通话记录关联数据的获取方法
4.封装便签属性访问方法
*/
package net.micode.notes.ui;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;

//用于封装便签数据，并提供对便签属性的访问方法
public class NoteItemData {
    //定义查询便签数据时需要的列
    static final String [] PROJECTION = new String [] {
        NoteColumns.ID,//便签唯一标识
        NoteColumns.ALERTED_DATE,//提醒日期时间戳
        NoteColumns.BG_COLOR_ID,//背景颜色资源ID
        NoteColumns.CREATED_DATE,//创建日期时间戳
        NoteColumns.HAS_ATTACHMENT,//是否有附件
        NoteColumns.MODIFIED_DATE,//最后修改时间戳
        NoteColumns.NOTES_COUNT,//子便签数量（用于文件夹）
        NoteColumns.PARENT_ID,//父级便签ID（用于层级结构）
        NoteColumns.SNIPPET,//便签摘要内容
        NoteColumns.TYPE,//便签类型（普通/文件夹/系统）
        NoteColumns.WIDGET_ID,//关联的小部件ID
        NoteColumns.WIDGET_TYPE,//小部件类型
    };

    //定义列索引常量
    private static final int ID_COLUMN                    = 0;
    private static final int ALERTED_DATE_COLUMN          = 1;
    private static final int BG_COLOR_ID_COLUMN           = 2;
    private static final int CREATED_DATE_COLUMN          = 3;
    private static final int HAS_ATTACHMENT_COLUMN        = 4;
    private static final int MODIFIED_DATE_COLUMN         = 5;
    private static final int NOTES_COUNT_COLUMN           = 6;
    private static final int PARENT_ID_COLUMN             = 7;
    private static final int SNIPPET_COLUMN               = 8;
    private static final int TYPE_COLUMN                  = 9;
    private static final int WIDGET_ID_COLUMN             = 10;
    private static final int WIDGET_TYPE_COLUMN           = 11;

    //便签属性
    private long mId;//便签ID
    private long mAlertDate;//提醒日期
    private int mBgColorId;//背景颜色ID
    private long mCreatedDate;//创建日期
    private boolean mHasAttachment;//是否有附件
    private long mModifiedDate;//修改日期
    private int mNotesCount;//便签数量
    private long mParentId;//父便签ID
    private String mSnippet;//便签摘要
    private int mType;//便签类型
    private int mWidgetId;//小部件ID
    private int mWidgetType;//小部件类型
    private String mName;//联系人姓名
    private String mPhoneNumber;//电话号码

    //便签位置信息
    private boolean mIsLastItem;//是否是最后一个便签
    private boolean mIsFirstItem; //是否是第一个便签
    private boolean mIsOnlyOneItem;//是否是唯一的便签
    private boolean mIsOneNoteFollowingFolder;//是否是一个便签跟随文件夹
    private boolean mIsMultiNotesFollowingFolder;//是否是多个便签跟随文件夹

    //构造函数，从数据库Cursor中初始化便签数据
    public NoteItemData(Context context, Cursor cursor) {
        //从Cursor中读取便签属性
        mId = cursor.getLong(ID_COLUMN);
        mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
        mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
        mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
        mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
        mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
        mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
        mParentId = cursor.getLong(PARENT_ID_COLUMN);
        mSnippet = cursor.getString(SNIPPET_COLUMN);
        mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
                NoteEditActivity.TAG_UNCHECKED, "");
        mType = cursor.getInt(TYPE_COLUMN);
        mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
        mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);

        //如果是通话记录文件夹中的便签，获取电话号码和联系人姓名
        mPhoneNumber = "";
        if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
            mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
            if (!TextUtils.isEmpty(mPhoneNumber)) {
                mName = Contact.getContact(context, mPhoneNumber);
                if (mName == null) {
                    mName = mPhoneNumber; //无联系人时使用号码本身
                }
            }
        }

        if (mName == null) {
            mName = "";
        }
        //检查便签的位置信息
        checkPostion(cursor);
    }

    private void checkPostion(Cursor cursor) {
        //基础位置判断
        mIsLastItem = cursor.isLast() ? true : false;
        mIsFirstItem = cursor.isFirst() ? true : false;
        mIsOnlyOneItem = (cursor.getCount() == 1);
        mIsMultiNotesFollowingFolder = false;
        mIsOneNoteFollowingFolder = false;

        //如果是便签类型且不是第一个便签，检查是否跟随文件夹
        if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
            int position = cursor.getPosition();
            if (cursor.moveToPrevious()) {
                if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
                        || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
                    if (cursor.getCount() > (position + 1)) {
                        mIsMultiNotesFollowingFolder = true;
                    } else {
                        mIsOneNoteFollowingFolder = true;
                    }
                }
                if (!cursor.moveToNext()) {
                    throw new IllegalStateException("cursor move to previous but can't move back");
                }
            }
        }
    }

    //

    //是否是一个便签跟随文件夹
    public boolean isOneFollowingFolder() {
        return mIsOneNoteFollowingFolder;
    }

    //是否是多个便签跟随文件夹
    public boolean isMultiFollowingFolder() {
        return mIsMultiNotesFollowingFolder;
    }

    //是否是最后一个便签
    public boolean isLast() {
        return mIsLastItem;
    }

    //获取联系人姓名
    public String getCallName() {
        return mName;
    }

    //是否是第一个便签
    public boolean isFirst() {
        return mIsFirstItem;
    }

    //是否是唯一的便签
    public boolean isSingle() {
        return mIsOnlyOneItem;
    }

    //获取便签ID
    public long getId() {
        return mId;
    }

    //获取提醒日期
    public long getAlertDate() {
        return mAlertDate;
    }

    //获取创建日期
    public long getCreatedDate() {
        return mCreatedDate;
    }

    //是否有附件
    public boolean hasAttachment() {
        return mHasAttachment;
    }

    //获取修改日期
    public long getModifiedDate() {
        return mModifiedDate;
    }

    //获取背景颜色ID
    public int getBgColorId() {
        return mBgColorId;
    }

    //获取父便签ID
    public long getParentId() {
        return mParentId;
    }

    //获取便签数量
    public int getNotesCount() {
        return mNotesCount;
    }

    //获取文件夹ID
    public long getFolderId () {
        return mParentId;
    }

    //获取便签类型
    public int getType() {
        return mType;
    }

    //获取小部件类型
    public int getWidgetType() {
        return mWidgetType;
    }

    //获取小部件ID
    public int getWidgetId() {
        return mWidgetId;
    }

    //获取便签摘要
    public String getSnippet() {
        return mSnippet;
    }

    //是否有提醒
    public boolean hasAlert() {
        return (mAlertDate > 0);
    }

    //是否是通话记录
    public boolean isCallRecord() {
        return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
    }

    //从Cursor中获取便签类型
    public static int getNoteType(Cursor cursor) {
        return cursor.getInt(TYPE_COLUMN);
    }
}
